import 'dart:async';
import 'package:flutter/services.dart';
export 'package:flutter/services.dart';

/// 定义通用回调
typedef MethodCallback<T> = dynamic Function(MethodCall call, T arg);

/// 定义调用原生后的回调
typedef OriginalCallback<T> = void Function(T arg);

/// 原生交互服务
class NativeService {
  /// 方法交互通道
  static const kSPMethodChannel = "speed_native_channel";

  /// 原生调用设置cookie
  static const String kNativeInvokeSetCookie = 'fromNativeCookie';

  /// 获取原生cookies
  static const String kMethodGetCookies = 'getCookieData';

  /// 为原生设置cookie（参数：flutterCookieData）
  static const String kMethodSetCookies = 'setCookieData';

  /// 删除原生所有cookie
  static const String kMethodDeleteCookies = 'deleteAllCookie';

  /// 打开原生控制器
  static const String kMethodOpenNative = 'openNativeController';

  /// 保存用户信息
  static const String kMethodSaveInfo = 'saveUserInfo';

  /// 充值中心支付
  static const String kMethodPayCenter = 'payFromVoucherCenter';

  /// 方法交互
  static const MethodChannel _channel = MethodChannel(kSPMethodChannel);

  /// 调用原生方法
  static Future<dynamic> invokeNative(String name,
      {dynamic data, OriginalCallback? callback}) async {
    switch (name) {
      case kMethodSetCookies:

        /// 为原生设置cookie
        return await _setCookieData();
      case kMethodDeleteCookies:

        /// 将原生cookie全部清除
        return await _deleteCookieData();
      case kMethodGetCookies:

        /// 获取原生cookie
        return await _getNativeCookies();
      default:
        throw PlatformException(
          code: 'Unimplemented',
          details: "Method $name not implemented",
        );
    }
  }

  /// 接收原生调用方法
  static void receiveNative(MethodCallback callback) {
    _channel.setMethodCallHandler((MethodCall call) async {
      if (call.method == kNativeInvokeSetCookie) {
        print("===来自原生设置cookie的参数==${call.arguments}");
      } else {
        return callback(call, '');
      }
    });
  }

  /// 获取原生cookies
  static Future<List<dynamic>> _getNativeCookies() async {
    List<dynamic> cookies = await _channel.invokeMethod(kMethodGetCookies);
    return cookies;
  }

  /// 将 Cookie 数据传递给原生
  static Future<dynamic> _setCookieData() async {
    String? cookie = "set-cookie";
    return await _channel
        .invokeMethod(kMethodSetCookies, {'flutterCookieData': cookie});
  }

  /// 将原生Cookie全部清除
  static Future<dynamic> _deleteCookieData() async {
    return await _channel.invokeMethod(kMethodDeleteCookies);
  }

  /// 打开原生页面并传值
  static Future<dynamic> openNative(dynamic data) async {
    return await _channel.invokeMethod(kMethodOpenNative, data);
  }

  /// 充值中心
  static Future<dynamic> voucherCenter(dynamic data) async {
    return await _channel.invokeMethod(kMethodPayCenter, data);
  }
}
